package com.hbnu.Control;


import com.hbnu.Pojo.DormBuild;
import com.hbnu.Pojo.PageModel;
import com.hbnu.Pojo.PageTag;
import com.hbnu.Pojo.User;
import com.hbnu.Service.DormManagerService;
import com.hbnu.Service.Impl.DormManagerServiceImp;
import com.hbnu.Service.Impl.UserServiceImpl;
import com.hbnu.Service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/student.action")
public class StudentServlet extends HttpServlet {
    DormManagerService dormManagerService = new DormManagerServiceImp();
    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String action = req.getParameter("action");

        String id = req.getParameter("id");
        String disabled = req.getParameter("disabled");

        User user = (User)req.getSession().getAttribute("session_user");

        Integer roleId = user.getRoleId();

        List<DormBuild> buildList = new ArrayList<DormBuild>();

        if (roleId.equals(0)) {
            buildList = dormManagerService.findAll();
        } else if (roleId.equals(1)) {
            buildList = dormManagerService.findByUserId(user.getId());
        }

        req.setAttribute("buildList", buildList);

        if ("list".equals(action)) {
            String dormId = req.getParameter("dormBuildId");
            String searchType = req.getParameter("searchType");
            String keyword = req.getParameter("keyword");

            String pageIndex = req.getParameter("pageIndex");

            PageModel pageModel = new PageModel();

            if (pageIndex != null && !pageIndex.isEmpty()) {
                pageModel.setPageIndex(Integer.parseInt(pageIndex));
            }

            List<User> students = userService.findStudent(dormId, searchType, keyword, user, pageModel);
            Integer totalNum = userService.findTotalNum(dormId, searchType, keyword, user);

            req.setAttribute("totalNum", totalNum);
            req.setAttribute("students", students);
            req.setAttribute("dormBuildId", dormId);
            req.setAttribute("searchType", searchType);
            req.setAttribute("keyword", keyword);
            req.setAttribute("students", students);
            req.setAttribute("pageIndex", pageModel.getPageIndex());
            req.setAttribute("mainRight", "/jsp/studentList.jsp");
            req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
        }
        else if ("preAdd".equals(action)) {
            List<DormBuild> dormBuilds = dormManagerService.findBuilds();


            req.setAttribute("builds", dormBuilds);
            req.setAttribute("mainRight", "/jsp/studentAddOrUpdate.jsp");
            req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
        }
        else if ("save".equals(action)) {
            String stuCode = req.getParameter("stuCode");
            String name = req.getParameter("name");
            String sex = req.getParameter("sex");
            String tel = req.getParameter("tel");
            String password = req.getParameter("passWord");
            String dormBuildId = req.getParameter("dormBuildId");
            String dormCode = req.getParameter("dormCode");

            User student = userService.findByStuCode(stuCode);

            if (id != null && !id.isEmpty()) {
                if (student != null && Integer.parseInt(id) != student.getId()){
                    req.getRequestDispatcher("/student.action?action=preUpdate&id=" + id).forward(req, resp);

                }
                else {
                    User studentUpdate = userService.findById(Integer.parseInt(id));
                    studentUpdate.setStuCode(stuCode);
                    studentUpdate.setName(name);
                    studentUpdate.setPassword(password);
                    studentUpdate.setSex(sex);
                    studentUpdate.setTel(tel);
                    studentUpdate.setDormBuildId(Integer.parseInt(dormBuildId));
                    studentUpdate.setDormCode(dormCode);
                    userService.updateStudent(studentUpdate);
                    resp.sendRedirect(getServletContext().getContextPath() + "/student.action?action=list");
                }
            }
            else {
                if (student != null) {
                    resp.sendRedirect(getServletContext().getContextPath() + "/student.action?action=preAdd");
                }
                else {
                    User user2 = new User();
                    user2.setStuCode(stuCode);
                    user2.setName(name);
                    user2.setPassword(password);
                    user2.setRoleId(2);
                    user2.setSex(sex);
                    user2.setTel(tel);
                    user2.setDormBuildId(Integer.parseInt(dormBuildId));
                    user2.setDormCode(dormCode);
                    user2.setCreateUserId(user.getId());
                    userService.saveStudent(user2);
                    resp.sendRedirect(getServletContext().getContextPath() + "/student.action?action=list");
                }
            }


        } else if ("preUpdate".equals(action)) {
            User userUpdate = userService.findById(Integer.parseInt(id));

            User user2 = userService.findByUserIdAndManager(userUpdate.getId(), user);

            if (user2 != null) {
                List<DormBuild> dormBuilds = dormManagerService.findBuilds();
                req.setAttribute("builds", dormBuilds);
                req.setAttribute("userUpdate", userUpdate);
                req.setAttribute("mainRight", "/jsp/studentAddOrUpdate.jsp");
                req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
            }
            else {
                resp.sendRedirect(getServletContext().getContextPath() + "/student.action?action=list");

            }
        }
        else if ("deleteOrActive".equals(action)) {
            User studentUpdate = userService.findById(Integer.parseInt(id));
            studentUpdate.setDisabled(Integer.parseInt(disabled));

            User user2 = userService.findByUserIdAndManager(studentUpdate.getId(), user);
            if (user2 == null) {
                System.out.println("null");
            }
            if (user2 != null) {
                userService.updateStudent(studentUpdate);
                resp.sendRedirect(getServletContext().getContextPath() + "/student.action?action=list");

            } else {
                resp.sendRedirect(getServletContext().getContextPath() + "/student.action?action=list");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
